package com.cory.module.job.service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cory.boot.base.BaseService;
import com.cory.module.job.domain.entity.JobExcelImport;
import com.cory.module.job.mapper.JobExcelImportMapper;

/**
 *  服务实现类
 *
 * @author xc
 * @since 2023-05-09
 */
@Service
public class JobExcelImportService extends BaseService<JobExcelImportMapper, JobExcelImport> {
    
    public List<JobExcelImport> list(JobExcelImport param) {
        QueryWrapper<JobExcelImport> query = new QueryWrapper<>();
        if (param.getTenantId() != null) {
            query.eq("tenant_id", param.getTenantId());
        }
        if (StringUtils.isNotBlank(param.getSystem())) {
            query.eq("system", param.getSystem());
        }
        if (param.getTargetId() != null) {
            query.eq("target_id", param.getTargetId());
        }
        if (param.getTargetType() != null) {
            query.eq("target_type", param.getTargetType());
        }
        if (StringUtils.isNotBlank(param.getType())) {
            if (param.getType().indexOf(",") >= 0) {
                query.in("type", Arrays.asList(param.getType().split(",")));
            } else {
                query.eq("type", param.getType());
            }
        }
        if (StringUtils.isNotBlank(param.getBusType())) {
            if (param.getBusType().indexOf(",") >= 0) {
                query.in("bus_type", Arrays.asList(param.getBusType().split(",")));
            } else {
                query.eq("bus_type", param.getBusType());
            }
        }

        query.orderByDesc("id");
        return super.list(query);
    }
    
    public synchronized List<JobExcelImport> runList(int size) {
        List<JobExcelImport> jobs = baseMapper.runList(size);
        if (jobs.size() > 0) {
            List<Integer> jobIds = jobs.stream().map(i -> i.getId()).collect(Collectors.toList());
            super.updateStateByIds(jobIds, 0);
        }
        return jobs;
    }
}
